/* eslint-disable no-param-reassign */
/* eslint-disable array-callback-return */
import { routerRedux } from 'dva/router';
import { message } from 'antd';
import { isLogin, login, fetchAuthorityList, logout } from '@/services/api';
import { disconnectSocket, isSocketEstablished } from '@/services/socket';
import { setAuthority } from '@/utils/authority';
import { reloadAuthorized } from '@/utils/Authorized';
import { Encrypt } from '@/utils/crypto';
import { delay } from '@/utils/dva';
import logo from '@/assets/defaultImg.png';

export default {
  namespace: 'login',

  state: {
    status: undefined,
    captcha: '/ssoApi/baselogin/captcha',
    baseUser: {},
    currentSystem: null,
    systemList: [],
    authorityList: [],
    visableModal: false,
    socketToken: '',
  },

  effects: {
    // 判断是否登录
    *isLogin(_, { call, put }) {
      const response = yield call(isLogin);
      if (response.success && response.data.baseUser) {
        window.sessionStorage.setItem(
          'firstLoginFlag',
          (response.data.baseUser && response.data.baseUser.firstLoginFlag) || 2
        );
        window.localStorage.setItem(
          window.btoa('userId'),
          window.btoa(response.data.baseUser && response.data.baseUser.userId) || ''
        );
        // 已登录
        response.data.baseSysList[0].isSelected = true;
        yield put({
          type: 'setLoginInfo',
          payload: {
            systemList: response.data.baseSysList,
            baseUser: { ...response.data.baseUser, avatar: logo },
          },
        });
        yield put({
          type: 'fetchAuthorityList',
          payload: {
            sysId: response.data.baseSysList[0].sysId,
          },
        });
      } else {
        yield put({
          type: 'getCaptcha',
        });
      }
    },
    // 登录
    *userLogin({ payload }, { call, put }) {
      const data = {};
      Object.entries(payload).forEach(([key, value]) => {
        data[key] = value;
        if (key === 'nutzer' || key === 'captcha') {
          data[key] = value.trim();
        } else {
          data[key] = Encrypt(value);
        }
      });
      const response = yield call(login, data);
      if (response.success && response.data.baseUser) {
        if (!response.data.baseSysList.length) {
          message.warning('抱歉，当前用户没有系统选择权限');
          yield put({
            type: 'logout',
          });
        }
        response.data.baseSysList.map(item => {
          item.isSelected = response.data.baseSysList.length === 1;
        });
        window.sessionStorage.setItem(
          'firstLoginFlag',
          (response.data.baseUser && response.data.baseUser.firstLoginFlag) || 2
        );
        window.localStorage.setItem(
          window.btoa('userId'),
          window.btoa(response.data.baseUser && response.data.baseUser.userId) || ''
        );
        yield put({
          type: 'setLoginInfo',
          payload: {
            systemList: response.data.baseSysList,
            baseUser: { ...response.data.baseUser, avatar: logo },
          },
        });
        if (response.data.baseSysList && response.data.baseSysList.length === 1) {
          // 单系统
          yield put({
            type: 'fetchAuthorityList',
            payload: {
              sysId: response.data.baseSysList[0].sysId,
            },
          });
        } else {
          yield put({
            type: 'setLoginStatus',
          });
        }
      } else {
        yield put({
          type: 'getCaptcha',
        });
        message.warning(response.message || '登录失败：服务端错误！');
      }
    },
    // 获取权限信息
    *fetchAuthorityList({ payload }, { call, put, select }) {
      const response = yield call(fetchAuthorityList, payload);
      if (response.success) {
        yield put({
          type: 'changeLoginStatus',
          payload: response.data,
        });
        reloadAuthorized();
        let sysUrl = yield select(state => {
          let url = '/';
          state.login.systemList.map(item => {
            if (item.isSelected) {
              url = item.sysUrl;
            }
          });
          return url;
        });
        const firstLoginFlag = window.sessionStorage.getItem('firstLoginFlag') || '2';
        if (firstLoginFlag === '1') {
          sysUrl = '/more/setting/security';
        }
        // 连接websocket
        yield put({
          type: 'socket/fetchSocketToken',
        });
        console.log('sysUrl: ', sysUrl);
        yield put(routerRedux.replace(sysUrl || '/'));
      } else {
        message.warning(response.message || '获取权限：服务端错误！');
      }
    },
    // 退出登录
    *logout(_, { call, put }) {
      const response = yield call(logout);
      yield put({
        type: 'setLoginInfo',
        payload: {
          systemList: [],
          baseUser: {},
        },
      });
      reloadAuthorized();
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          currentAuthority: '',
        },
      });
      disconnectSocket();
      if (response.success) {
        // 2020-07-29 解决单页面重复登录退出切换用户页面崩溃问题
        // 清空缓存和登录信息
        localStorage.clear();
        sessionStorage.clear();
        document.cookie = '';
        window.location.href = `/user/login?_=${new Date().getTime()}`;
        // 原操作
        // yield put(
        //   routerRedux.replace({
        //     pathname: '/user/login',
        //   })
        // );
      } else {
        message.warning(response.message);
      }
    },
    /**
     * 设置当前系统sysId
     * @param {currentSystem} payload
     *
     */
    *setCurrentSystemBySysID({ payload }, { put, select }) {
      const systemList = yield select(state => state.login.systemList);
      const { sysId } = payload;
      const currentSystem = systemList.find(system => system.sysId === sysId);
      if (currentSystem) {
        yield put({
          type: 'setCurrentSystem',
          payload: { currentSystem: { ...currentSystem } },
        });
      } else {
        throw new Error('没有找到选中的系统');
      }
    },
    /**
     * 系统切换
     * @param {sysId, routes, authority} payload
     *
     */
    *systemChange({ payload }, { put, select }) {
      const loginState = yield select(state => state.login);
      const routing = yield select(state => state.routing);
      const { currentSystem, systemList } = loginState;
      const { sysId, routes, authority } = payload;
      if (currentSystem.sysId === sysId) {
        return;
      }
      const newSystemList = systemList.map(system => ({
        ...system,
        isSelected: system.sysId === sysId,
      }));
      const newCurrentSystem = newSystemList.find(system => system.sysId === sysId);
      yield put({
        type: 'setSystemList',
        payload: {
          systemList: newSystemList,
        },
      });
      yield put.resolve({
        type: 'setCurrentSystem',
        payload: {
          currentSystem: newCurrentSystem,
        },
      });

      // 渲染1秒钟
      yield delay();

      yield put.resolve({
        type: 'fetchAuthorityList',
        payload: { sysId },
      });
      yield put.resolve({
        type: 'setting/getSetting',
      });
      yield put.resolve({
        type: 'menu/getMenuData',
        payload: { routes, authority },
      });

      if (routing.location.pathname === '/home/workplace/index') {
        yield put({
          type: 'workplace/updateModalData',
          payload: {
            shortcutChosen: [],
            shortcutList: [],
            waitTaskData: [],
            shortcutData: [],
            noticeData: [],
            chosenKeys: [],
          },
        });
        yield put({
          type: 'workplace/searchWaitTask',
        });
        yield put({
          type: 'workplace/searchNotice',
        });
        yield put({
          type: 'workplace/searchFunParams',
        });
      }
    },
  },

  reducers: {
    // 更改登录状态:设置权限
    changeLoginStatus(state, { payload }) {
      setAuthority(payload);
      return {
        ...state,
        // status: true,
      };
    },
    // 获取验证码
    getCaptcha(state) {
      return {
        ...state,
        captcha: `/ssoApi/baselogin/captcha?t=${new Date().getTime()}`,
      };
    },
    setCurrentSystem(state, { payload }) {
      return {
        ...state,
        currentSystem: payload.currentSystem,
      };
    },
    setSystemList(state, { payload }) {
      return {
        ...state,
        systemList: payload.systemList,
      };
    },
    // 更改登录信息
    setLoginInfo(state, { payload }) {
      return {
        ...state,
        ...payload,
        visableModal: false,
      };
    },
    // 更改弹框显隐：显示
    setLoginStatus(state) {
      return {
        ...state,
        visableModal: true,
      };
    },
    // 更改用户名
    updateUserName(state, { payload }) {
      return {
        ...state,
        baseUser: {
          ...state.baseUser,
          userName: payload.userName,
          userPortrait: payload.userPortrait,
        },
      };
    },
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
